package cn.chinamobile.controller;

import cn.chinamobile.dao.OrderDao;
import cn.chinamobile.entities.Bus;
import cn.chinamobile.entities.CommonResult;


import cn.chinamobile.entities.Order;
import cn.chinamobile.entities.OrderVO;
import com.sun.org.apache.xpath.internal.operations.Or;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Slf4j
@CrossOrigin
public class OrderController {

    @Autowired
    private OrderDao orderDao;

    @RequestMapping(value = "/order/query", method = RequestMethod.GET)
    public CommonResult query(@RequestParam Integer userId){
        List<Order> orderList = orderDao.getOrderByUserId(userId);

        List<OrderVO> orderVOList = new ArrayList<OrderVO>();
        if(orderList == null){
            return new CommonResult(200,"暂无订单", orderVOList);
        }
        for (int i = 0; i < orderList.size(); i++) {
            Bus bus = orderDao.getBusById(orderList.get(i).getBusId());
            OrderVO order = new OrderVO();

            order.setOrderId(orderList.get(i).getId());
            order.setTime(orderList.get(i).getTime());
            order.setArrivalStation(bus.getArrivalStation());
            order.setStartStation(bus.getStartStation());
            order.setCapacity(bus.getCapacity());
            order.setBusId(bus.getId());
            order.setFrequency(bus.getFrequency());
            order.setDepartureTime(bus.getDepartureTime());
            order.setStops(bus.getStops());
            order.setUserId(orderList.get(i).getUserId());

            orderVOList.add(order);

        }
        return new CommonResult(200,"查询成功", orderVOList);
    }

    @RequestMapping(value = "/order/add", method = RequestMethod.GET)
    public CommonResult add(@RequestParam Integer userId, String busId){
        Date date = new Date();

        Order order = new Order();
        order.setUserId(userId);
        order.setBusId(busId);
        order.setTime(date);
        int result = orderDao.orderAdd(order);
        if (result == 0){
            return new CommonResult(400,"订票失败");
        }else {
            return new CommonResult(200,"订票成功", order);
        }
    }

    @RequestMapping(value = "order/delete", method = RequestMethod.GET)
    public CommonResult delete(@RequestParam Integer id){
        int result = orderDao.orderDelete(id);
        if(result == 0){
            return new CommonResult(400,"删除失败");
        }else{
            return new CommonResult(200,"删除成功");
        }
    }



}
